#include <WiFiManager.h>
#include <EEPROM.h>
#include "GpioButton.h"
#include "Blwifi.h"

WiFiManager wifiManager;

void ResetWifi()
{
  ClearWiFiInfo();
  wifiManager.resetSettings();
  ESP.restart();
}

void mbt_press_callback()
{
#ifdef SUPPORT_DEBUG
  Serial.println("<Event>Click");
#endif

}

void mbt_long_press_callback()
{
#ifdef SUPPORT_DEBUG
  Serial.println("<Event>Long Press Tick");
  Serial.println(F("WiFi resetSettings."));
#endif
  for (int i = 0; i < 3; i++)
  {
    delay(500);
    digitalWrite(LED_IO, LOW);
    delay(500);
    digitalWrite(LED_IO, HIGH);
    delay(500);
  }
  ResetWifi();
}

// 定义按钮对象，指定按钮的GPIO口
GpioButton myButton(RESET_WIFI_PIN);

bool shouldSaveConfig = false;
Settings wifiSettings;

void saveConfigCallback()
{
#ifdef SUPPORT_DEBUG
  Serial.println("Should save config");
#endif
  shouldSaveConfig = true;
}

bool chkAuthkey(char* key, int len)
{
  if (len != 32) return false;
  for (int i = 0; key[i] != 0; i++) {
    if (!isxdigit(key[i])) return false;
  }
  return true;
}
void ClearWiFiInfo()
{
  EEPROM.begin(1280);
  EEPROM.get<Settings>(1024, wifiSettings);
  wifiSettings.auth_key[0] = '\0';
  wifiSettings.topic[0] = '\0';
  EEPROM.put<Settings>(1024, wifiSettings);
  if (EEPROM.commit())
  {
#ifdef SUPPORT_DEBUG
    Serial.println(F("EEPROM successfully committed"));
#endif
  }
  else
  {
#ifdef SUPPORT_DEBUG
    Serial.println(F("ERROR! EEPROM commit failed"));
#endif
  }
  EEPROM.end();
}
void Blwifi_InitWiFi()
{
  myButton.bindEventOnClick(mbt_press_callback);
  myButton.bindEventOnLongPress(mbt_long_press_callback);

  EEPROM.begin(1280);
  EEPROM.get<Settings>(1024, wifiSettings);

  if ( wifiSettings.auth_key[0] == '\0' || wifiSettings.auth_key[0] == 0xFF)
  {
    WiFi.mode(WIFI_STA);
    //wifiManager.setDebugOutput(true);

    wifiManager.resetSettings();

    wifiManager.setAPStaticIPConfig(IPAddress(192, 168, 10, 1), IPAddress(192, 168, 10, 1), IPAddress(255, 255, 255, 0));
    // 3分钟配网时间,如没有完成则退出配网.
    // 例如原正常连接的WIFI路由掉线死机或不通电等情况, 通过配网超时后, 会重新进行连接原WIFI信号。 避免停在配网模式下等待
    wifiManager.setConfigPortalTimeout(180);

    // 设置点击保存的回调
    wifiManager.setSaveConfigCallback(saveConfigCallback);

    WiFiManagerParameter custom_authkey("auth_key", "Authkey", wifiSettings.auth_key, 32);
    wifiManager.addParameter(&custom_authkey);

    WiFiManagerParameter custom_topic("topic", "topic", wifiSettings.topic, 32);
    wifiManager.addParameter(&custom_topic);

    //AP名称：ESP_AP 密码：12345678
    if (!wifiManager.autoConnect("ESP_AP", "12345678"))
    {
#ifdef SUPPORT_DEBUG
      Serial.println(F("Failed to connect. Reset and try again. . ."));
#endif
      ResetWifi();
      delay(5000);
    }
#ifdef SUPPORT_DEBUG
    Serial.println(F("Connected to Wifi."));
    Serial.print(F("My IP:"));
    Serial.println(WiFi.localIP());
#endif

    // 保存自定义信息
    if (shouldSaveConfig)
    {
#ifdef SUPPORT_DEBUG
      Serial.println(F("saving config..."));
#endif
      Serial.println(custom_authkey.getValue());
      strncpy(wifiSettings.auth_key, custom_authkey.getValue(), 32);
      wifiSettings.auth_key[32] = '\0';
      Serial.println(custom_topic.getValue());
      strncpy(wifiSettings.topic, custom_topic.getValue(), 32);
      wifiSettings.topic[32] = '\0';
      strcpy(wifiSettings.ssid, wifiManager.getWiFiSSID().c_str());
      wifiSettings.ssid[wifiManager.getWiFiSSID().length()] = '\0';

      strcpy(wifiSettings.pswd, wifiManager.getWiFiPass().c_str());
      wifiSettings.pswd[wifiManager.getWiFiPass().length()] = '\0';

      if (!chkAuthkey(wifiSettings.auth_key, strlen(wifiSettings.auth_key)))
      {
#ifdef SUPPORT_DEBUG
        Serial.println(F("Authkey is wrong."));
#endif
        ResetWifi();
        delay(5000);
      }

      EEPROM.put<Settings>(1024, wifiSettings);
      if (EEPROM.commit())
      {
#ifdef SUPPORT_DEBUG
        Serial.println(F("EEPROM successfully committed"));
#endif
      }
      else
      {
#ifdef SUPPORT_DEBUG
        Serial.println(F("ERROR! EEPROM commit failed"));
#endif
      }
      ESP.restart();
    }
  }
  EEPROM.end();
  wifiSettings.auth_key[32] = '\0';
  wifiSettings.topic[32] = '\0';
}

void Blwifi_Loop()
{
  myButton.loop();
}
